// 本地OS随机bind
#include <iostream>

#include <string>
#include <cstring>
#include <errno.h>

#include "Log.hpp"
#include "Comm.hpp"

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "Thread.hpp"
#include "InetAddr.hpp"
void Usage(std::string &&str)
{
    std::cout << "格式: " << str << " serverip serverport" << std::endl;
}

class ThreadData
{
public:
    ThreadData(int sockfd, const struct sockaddr_in &addr)
        : _sockfd(sockfd), _addr(addr)
    {
    }

public:
    int _sockfd;
    InetAddr _addr;
};
void ReveiveRoutine(ThreadData &data)
{
    while (1)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len;
        int m = recvfrom(data._sockfd, buffer, 1023, 0, (struct sockaddr *)&peer, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cerr << buffer << std::endl; //mkfifo观察
        }
        else
            break;
    }
}
void SendRoutinue(ThreadData &data)
{
    while (1)
    {
        std::string str;
        std::cout << "输入需要发送的内容" << std::endl;
        getline(std::cin, str);
        struct sockaddr_in server = data._addr.GetAddr();
        ssize_t n = sendto(data._sockfd, str.c_str(), str.size(), 0, (struct sockaddr *)&server, sizeof server);
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return usage_err;
    }
    // 1.创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        lg.LogMessage(Error, "create sockfd failed, errno: %d, %s\n", errno, strerror(errno));
        return sockfd_err;
    }

    // 2.自动bind一个随机的当前不被使用的端口号
    //...

    // 配置服务器地址信息(服务器网络端点)
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(argv[1]);
    server.sin_port = htons(std::stoi(argv[2]));

    ThreadData data(sockfd, server);

    Thread<ThreadData> receive_thread("receive", ReveiveRoutine, data);
    Thread<ThreadData> send_thread("send", SendRoutinue, data);

    receive_thread.Start();
    send_thread.Start();

    receive_thread.Join();
    send_thread.Join();

    return 0;
}